package com.research.web.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.research.web.entity.UserEntity;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import static com.research.web.utils.DruidUtils.closeConnection;

public class UserServiceUtils {
    private static final String INSERT_USER = "insert into sys_user (id, user_name, password, update_time) "
            + "#{values} "
            + "on duplicate key update id=values(id), user_name=values(user_name), password=values(password), update_time=values(update_time) ";

    public static boolean saveOrUpdateBatch(DruidDataSource druidDataSource, List<UserEntity> userEntityList) throws Exception {
        String name = druidDataSource.getName();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        DruidPooledConnection connection = null;
        try {
            connection = druidDataSource.getConnection();
            String sql = INSERT_USER.replace("#{values}", getValues(userEntityList));
            System.out.println(name + "系统，更新sql为：" + sql);
            preparedStatement = connection.prepareStatement(sql);
            int i = preparedStatement.executeUpdate();
            System.out.println(name + "更新记录：" + i);
        } catch (Exception e) {
            throw new RuntimeException("数据查询失败:" + e);
        } finally {
            closeConnection(connection, preparedStatement, resultSet);
        }
        return false;
    }

    /**** 拼装批量插入sql语句 ***/
    private static String getValues(List<UserEntity> userEntities) {
        String values = "values";
        for (UserEntity userEntity : userEntities) {
            values += "(" + userEntity.getId() + ",'"
                    + userEntity.getUserName() + "','"
                    + userEntity.getPassword() + "','"
                    + userEntity.getUpdateTime() + "'),";
        }
        values = values.substring(0, values.length() - 1);
        return values;
    }
}
